package org.ocean.online.web.workspace;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.HiddenField;
import org.apache.wicket.model.Model;
import org.ocean.online.constant.Constant;
import org.ocean.online.sys.DbGuard;
import org.ocean.online.utils.CommonUtil;
import org.ocean.online.wicket.NeedLoginPage;

public class WorkSpace2 extends NeedLoginPage{

	private static final long serialVersionUID = 6594634024660881672L;

	HiddenField<String> username = new HiddenField<String>(Constant.Username_VariableName,new Model());
	public WorkSpace2(){
		username.setDefaultModelObject(this.getUsername());
		add(username);
		Form<?> form = new Form("ajaxForm",new Model());
		add(form);
		AjaxSubmitLink editNode = new AjaxSubmitLink("editNode",form) {
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				try{
					editNode(target);
				}catch(Exception ex){
					target.appendJavaScript("alert('"+ex.getMessage()+"');");
					target.appendJavaScript("editSelected();");
				}
			}
		};
		AjaxSubmitLink removeNode = new AjaxSubmitLink("removeNode") {
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				removeNode(target);
			}
		};
		
		AjaxSubmitLink paste = new AjaxSubmitLink("paste") {
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				String copyPath = target.getPage().getRequest().getRequestParameters().getParameterValue("copyPath").toString();
				String pastePath = target.getPage().getRequest().getRequestParameters().getParameterValue("path").toString();
				if(copy(copyPath,pastePath)){
					target.appendJavaScript("refresh();");
				}
			}

			private boolean copy(String copyPath, String pastePath) {
				
				File copyFile = new File(getWorkspace()+copyPath);
				File destFile = new File(getWorkspace()+pastePath+File.separator+"copy of "+ copyFile.getName());
				try {
					if(copyFile.isFile()){
						FileUtils.copyFile(copyFile, destFile);
					}else if(copyFile.isDirectory()){
						FileUtils.copyDirectory(copyFile, destFile);
					}
				} catch (IOException e) {
					return false;
				}
				return true;
			}
		};
		form.add(editNode);
		form.add(removeNode);
		form.add(paste);
		
		AjaxLink logout = new AjaxLink("logout"){

			@Override
			public void onClick(AjaxRequestTarget target) {
				getHttpSession().removeAttribute("user");
				target.appendJavaScript("window.location='login'");
			}
		};
		add(logout);
	}
	
	private void editNode(AjaxRequestTarget target) throws IOException{
		String oldPath=target.getPage().getRequest().getRequestParameters().getParameterValue("oldPath").toString("");
		String path=target.getPage().getRequest().getRequestParameters().getParameterValue("path").toString("");
		String type=target.getPage().getRequest().getRequestParameters().getParameterValue("type").toString("");
		File file = new File(this.getWorkspace()+path);
		if(file.exists()){
			throw new RuntimeException("file is already exsit");
		}
		if(StringUtils.isBlank(oldPath)){
			//new
			if("package".equals(type)){
				file.mkdir();
			}else if("file".equals(type)){
				file.createNewFile();
			}else{
				throw new RuntimeException("type of node unknown");
			}
			target.appendJavaScript("updateNodeState()");
		}else{
			//modify
			File oldFile= new File(this.getWorkspace()+oldPath);
			try {
				// try to see whether file name is all right
				file.createNewFile();
			}finally{
				file.delete();
			}
			if(CommonUtil.getExtOfFile(oldFile.getName()).equalsIgnoreCase("model")){
				String update ="update model set 'projectName'=? where 'projectName'=?";
				getDb().execute(update, file.getName(),oldFile.getName());
			}
			oldFile.renameTo(file);
		}
	}
	
	private void removeNode(AjaxRequestTarget target){
		try{
			String path=target.getPage().getRequest().getRequestParameters().getParameterValue("path").toString("");
			File file = new File(this.getWorkspace()+path);
			String ext =CommonUtil.getExtOfFile(file.getPath());
			
			if("model".equalsIgnoreCase(ext)){
				String fileName = file.getName();
				// delete model from db;
				DbGuard db = this.getDb();
				String sql = "select 'modelName' from model where 'projectName'=? group by 'modelName'";
				List<Map> models = db.query(sql, fileName);
				for(Map map : models){
					String modelName = map.get("modelName").toString();
					String del = "delete from model where 'projectName'=? and 'modelName'=?";
					String drop = "drop table "+modelName;
					db.execute(drop);
					db.execute(del, fileName,modelName);
				}
			}
			if(file.exists()){
				FileUtils.deleteQuietly(file);
			}
		}catch(Exception ex){
			target.appendJavaScript("delete node failed");
		}
	}
	
	
}
